package heliotrope.game.scene.map
{
	import flash.display.Bitmap;
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.geom.Point;
	
	import heliotrope.display.AutoBitmap;
	import heliotrope.global.GlobalVar;
	import heliotrope.res.BitmapAttacher;
	import heliotrope.res.BitmapdataDistributor;
	import heliotrope.res.GraphicResource;
	import heliotrope.res.ResourcePool;
	import heliotrope.res.TileResource;

	public class Map
	{
		private var _id:uint;
		private var _resourceId:uint;
		private var _width:uint,_height:uint;
		private var _tileWidth:uint,_tileHeight:uint; 
		private var _tileNumX:uint,_tileNumY:uint;
		private var _x:Number,_y:Number;
		
		private var _thumb:Sprite;
		private var _tile:Sprite;
		
		private var _tileGetter:Function;
		private var _stage:Stage;
		public function Map(opts:Object)
		{
			_id 		= opts["id"];
			_resourceId = opts["resourceId"];
			_width 		= opts["width"];
			_height 	= opts["height"];
			_tileWidth 	= opts["tileWidth"];
			_tileHeight = opts["tileHeight"];
			_tileNumX 	= _width/_tileWidth;
			_tileNumY 	= _height/_tileHeight;
			_x=_y= 0;
			_stage = GlobalVar.getInstance().stage;
			var res:TileResource = ResourcePool.getInstance().graphics.tilesets.getRes(_resourceId);
			_tileGetter = res.getTile;
			
			_thumb = new Sprite;
			var thumbMap:BitmapAttacher = new BitmapAttacher;
			res.getThumb().attach(thumbMap);
			_thumb.addChild(thumbMap);
			_thumb.width = _width, _thumb.height = _height;
			
			_tile = new Sprite;
//			addChild(thumbMap);
//			refreshTiles();
		}

		public function update():void
		{
			_tile.removeChildren();
			var rangeX:int = Math.ceil(_stage.stageWidth/_tileWidth);
			var rangeY:int = Math.ceil(_stage.stageHeight/_tileHeight);
			var startX:int = (-_x)/_tileWidth;
			var startY:int = (-_y)/_tileHeight;
			var endX:int = (startX+rangeX)<(_tileNumX)?startX+rangeX+1:_tileNumX;
			var endY:int = (startY+rangeY)<(_tileNumY)?startY+rangeY+1:_tileNumY;
			for(var i:int = startX; i<endX; i++)
			{
				for(var j:int = startY; j<endY; j++)
				{
					var mapTile:AutoBitmap = _tileGetter(i, j);
					mapTile.x = i*_tileWidth;
					mapTile.y = j*_tileHeight;
					_tile.addChild(mapTile);
				}
			}
		}

		public function localToGlobal(localP_:Point):Point
		{
			return new Point(localP_.x+_x, localP_.y+_y);
		}
		
		public function get id():uint{return _id;}

		public function get thumb():Sprite{return _thumb;}
		public function get tile():Sprite{return _tile;}

		public function get width():uint{return _width;}
		public function get height():uint{return _height;}


		public function get x():Number{return _x;}
		public function set x(value_:Number):void
		{
			_x = value_;
		}

		public function get y():Number{return _y;}
		public function set y(value_:Number):void
		{
			_y = value_;
		}


	}
}